
#include <cctype>
#include <cmath>
#include <BFile>
#include <BJsonDocument>

#include "member_BJsonDocument.h"

using namespace BWE;

#define member					(*(member_BJsonDocument*)_ptr)
#define member_allocate()		_ptr = new member_BJsonDocument(this)
#define member_release()		delete (member_BJsonDocument*)_ptr

BJsonDocument::BJsonDocument()
{
	member_allocate();
}
BJsonDocument::~BJsonDocument()
{
	member_release();
}

bool BJsonDocument::parse(const BString& text)
{
    member.pos = 0;
	member.root = member.parseValue(text);
    return !member.root.empty();
}
bool BJsonDocument::serialize(BString& text, bool pretty) const
{
	text = member.serialize(member.root, pretty ? 2 : 0);
	return text.size();
}

bool BJsonDocument::loadFile(const BString& filePath)
{
	BString content;
	if (!BFile::Load(filePath, content))
	{
		member.message() << "Cannot open file: " << filePath << '\n';
		return false;
	}
	return this->parse(content);
}
bool BJsonDocument::saveFile(const BString& filePath, bool pretty) const
{
	BString text = member.serialize(member.root, pretty);
	if (!BFile::Save(filePath, text))
		return false;
	return true;
}

BJsonObject& BJsonDocument::root()
{
	return member.root.fill<BJsonObject>();
}
const BJsonObject& BJsonDocument::root() const
{
	return member.root;
}

void BJsonDocument::clear()
{
	member.root.clear();
}
